// pages/submit-order/submit-order.js
var api = require('../../config/api.js');
var util = require('../../utils/util.js');
Page({

  /**
   * 页面的初始数据
   */
  data: {

    showPayType: false,
    showCoupon: false,
    showBill: false,
    showOverlay: false,
    isChoose: false,
    active: 0,
    list1: [
      false, true
    ],
    //发票类型
    billType: 1,
    billContentType: 1,
    explainList: [
      '电子发票是税局认可的有效收付款凭证，其法律效力、基本用途及使用规定同纸质发票，支持报销入账，如需纸质发票可自行下载打印',
      '电子发票是税局认可的有效收付款凭证，其法律效力、基本用途及使用规定同纸质发票，支持报销入账，如需纸质发票可自行下载打印',
      '电子发票是税局认可的有效收付款凭证，其法律效力、基本用途及使用规定同纸质发票，支持报销入账，如需纸质发票可自行下载打印'
    ],
    cartId: 0,
    addressId: 0,
    couponId: 0,
    userCouponId: 0,
    strMessage: '',
    showPaying: false,
    cardName: ''
  },

  //获取订单数据
  getData() {
    let that = this;
    util.request(api.GiftOrderAffirm, {
      products: that.data.products
    }, 'post').then(function(res) {
      if (res.errno == 0) {

        that.setData({
          goodsList: res.data.products,
          totNum: res.data.totNum,
          totPrice: res.data.totPrice
        })

      } else {
        util.myToast(res.errmsg)
      }
    });
  },
  //提交订单
  getSubData() {
    let that = this;
    util.request(api.SubmitGiftOrder, {
      totPrice: that.data.totPrice,
      giftName: that.data.cardName,
      products: that.data.products,
      shareUserId: util.isEmpy(wx.getStorageSync("shareUserId")) ? '' : util.isEmpy(wx.getStorageSync("shareUserId"))
    }, 'post').then(function(res) {
      if (res.errno == 0) {
        var merReqNo = res.data.orderSn;
        var orderid = res.data.orderId;
        that.setData({
          orderid: orderid
        })
        if (that.data.isChoose) {
          //余额支付
          that.getBanlenceData(merReqNo)
        } else {
          //微信支付
          that.onWeChatPay(merReqNo);
        }
      } else {
        util.myToast(res.errmsg)
      }
    });
  },
  //获取卡片名称
  getCardName(e) {
    this.setData({
      cardName: e.detail.value
    })
  },
  //微信支付
  onWeChatPay: function(merReqNo) {
    let that = this;
    that.setData({
      showPaying: true
    })

    wx.login({
      success: res => {
        var code = res.code;
        util.request(api.StartPay, {
          merReqNo: merReqNo,
          code: code
        }, 'POST').then(function(res) {
          if (res.respCode == 'ZB0000') {
            var payParam = res;
            wx.requestPayment({
              'timeStamp': payParam.timestamp,
              'nonceStr': payParam.noncestr,
              'package': payParam.package,
              'signType': payParam.signtype,
              'paySign': payParam.paysign,
              'success': function(res) {
                //支付成功
                util.toClassFinish('/pages/card_payment/card_payment', {
                  money: that.data.totPrice,
                  orderid: that.data.orderid
                })

                that.setData({
                  showPaying: false
                })

              },
              'fail': function(res) {
                //支付失败
                that.setData({
                  showPaying: false
                })
                wx.redirectTo({
                  url: '/pages/send-order-list/send-order-list',
                })
              },
            });
          } else {
            if (util.isEmpy(res.respDesc)) {
              util.myToast(res.errmsg);
            } else {
              util.myToast(res.respDesc);
            }
            that.setData({
              showPaying: false
            })
            wx.redirectTo({
              url: '/pages/send-order-list/send-order-list',
            })
          }
        });

      }
    })

  },
  //余额支付
  getBanlenceData(merReqNo) {
    let that = this;
    that.setData({
      showPaying: true
    })
    util.request(api.BalancePay, {
      merReqNo: merReqNo
    }, 'post').then(function(res) {
      if (res.errno == 0) {
        that.setData({
          showPaying: false
        })
        //支付成功
        util.toClassFinish('/pages/card_payment/card_payment', {
          money: that.data.totPrice,
          orderid: that.data.orderid
        })
      } else {
        that.setData({
          showPaying: false
        })
        util.myToast(res.errmsg)
      }
    });
  },
  //获取订单备注信息
  getMessage(e) {
    this.setData({
      strMessage: e.detail.value
    })
  },



  //弹出选择支付方式
  openPayWindow(e) {
    this.getUserData();
    this.setData({
      showPayType: true
    })
  },
  //关闭弹窗
  onClose(e) {
    this.setData({
      showPayType: false,
      showCoupon: false,
      showBill: false,
      showOverlay: false
    })
  },
  //选择余额
  onChooseYue(e) {
    if (this.data.balance > 0 && this.data.bean.actualPrice <= this.data.balance) {
      this.setData({
        isChoose: true
      })
    }
  },
  //选择微信
  onChooseWechat(e) {
    this.setData({
      isChoose: false
    })
  },
  //确认使用
  onSurePay(e) {
    this.setData({
      showPayType: false
    })
  },


  //弹出发票
  // onShowBill(e) {
  //   this.setData({
  //     showBill: true
  //   })
  // },
  //点击企业
  onFirm(e) {
    this.setData({
      billType: 1
    })
  },
  //点击个人
  onPerson(e) {
    this.setData({
      billType: 2
    })
  },
  //点击商品明细
  onGoodsDetails(e) {
    this.setData({
      billContentType: 1
    })
  },
  //点击商品类别
  onGoodsType(e) {
    this.setData({
      billContentType: 2
    })
  },
  //开票规则
  onUseRule(e) {
    this.setData({
      showOverlay: true
    })
  },
  //发票须知我知道了
  onKnow(e) {
    this.setData({
      showOverlay: false
    })
  },
  //选择收货地址
  onChooseAddress(e) {
    wx.navigateTo({
      url: '/pages/address/address',
    })
  },
  //点击提交订单
  onSubmit: util.throttle(function(e) {
    this.getSubData();
  }, 1500),

  //获取用户数据
  getUserData() {
    let that = this;
    util.request(api.Center).then(function(res) {
      if (res.errno == 0) {
        that.setData({
          balance: res.data.user.balance
        })

      } else {
        util.myToast(res.errmsg)
      }
    });
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {

    var products = JSON.parse(options.products);
    console.log("produ---", products);

    this.setData({
      products: products
    })

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {
    const pages = getCurrentPages()
    const currPage = pages[pages.length - 1] // 当前页
    var addressid = currPage.data.addressid;
    addressid = util.isEmpy(addressid) ? '0' : addressid;
    console.log("addressid--", addressid)
    this.setData({
      addressId: addressid
    })
    this.getData();
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {

  }
})